package org.yi.core.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.yi.core.common.GlobalCache;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

public class SessionInterceptor implements Interceptor {
	
	@Override
	public void intercept(Invocation i) {
		
		//if user has authenticated, invoke next interceptor
		if(SecurityUtils.getSubject().isAuthenticated()){
			i.invoke();
		} else {
			//else redirect to login page
			Controller c = i.getController();
			//if session is null, redirect to login page
			if(SecurityUtils.getSubject().getSession() != null) {
				if(isExcludeFromSession(c.getRequest().getRequestURI())){
					i.invoke();
				} else {
					c.redirect("/login");
				}
			} else {
				c.redirect("/login");
			}
		}
	}
	
	/**
	 * exclude uri from session
	 * @param requestURI
	 * @return
	 */
	private static Boolean isExcludeFromSession(String requestURI) {
		if(StringUtils.isBlank(requestURI)) {
			return true;
		}
		String[] excludeURI = GlobalCache.config.getStringArray("session.exclude");
		for(String uri : excludeURI) {
			if(requestURI.contains(uri)) {
				return true;
			}
		}
		return false;
	}

}
